/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-8-24 上午10:59 Created by lyyang
 */
package com.jade.bss.base.blacklist.impl;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jade.bss.base.blacklist.BlackList;
import com.jade.bss.base.blacklist.BlackListDao;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;

/**
 * 黑名单dao,jpa实现
 *
 * @author <a href="mailto:lyyang@ceno.cn">lyyang</a>
 * @version 1.0 15-8-24 上午10:59
 */
@Named ("bss_blackListDao")
public class JpaBlackListDao implements BlackListDao
{
    
    @PersistenceContext (unitName = "default")
    private EntityManager entityManager;

    public long add(BlackList blackList) {
        entityManager.persist(blackList);
        return blackList.getId();
    }

    public void update(BlackList blackList){
        entityManager.merge(blackList);
    }

    public void remove(BlackList blackList){
        entityManager.remove(blackList);
    }

    public BlackList get(long id){
        return entityManager.find(BlackList.class,id);
    }

    public PagingList<BlackList> query(Criteria criteria){
        String sql = "SELECT blackList FROM BlackList blackList";
        return SqlUtils.sqlQuery(sql, entityManager, criteria);
    }

    public List<BlackList> list(Criteria criteria){
        String sql = "SELECT blackList FROM BlackList blackList";
        return SqlUtils.sqlQueryWithoutCount(sql,entityManager,criteria);
    }

    public void remove(String ownerType,String ownerId,String blockType,String blockId){
        String sql = "DELETE FROM BlackList WHERE ownerType=:ownerType AND ownerId=:ownerId " +
                     "AND blockType=:blockType AND blockId=:blockId";
        Query query = entityManager.createQuery(sql);
        query.setParameter("ownerType",ownerType);
        query.setParameter("ownerId",ownerId);
        query.setParameter("blockType",blockType);
        query.setParameter("blockId",blockId);
        query.executeUpdate();
    }

    public BlackList get(String ownerType,String ownerId,String blockType,String blockId){
        String sql = "SELECT blacklist FROM BlackList blacklist WHERE ownerType=:ownerType AND ownerId=:ownerId " +
                     "AND blockType=:blockType AND blockId=:blockId";
        Query query = entityManager.createQuery(sql);
        query.setParameter("ownerType",ownerType);
        query.setParameter("ownerId",ownerId);
        query.setParameter("blockType",blockType);
        query.setParameter("blockId",blockId);
        try {
            return (BlackList)query.getSingleResult();
        }
        catch (NoResultException e) {

        }
        return null;
    }
    
}
